﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace SharpSoft.WPF
{
    public class JTokenDefaultConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                if (targetType.IsClass)
                {
                    return null;
                }
                if (targetType.IsGenericType&&targetType.GetGenericTypeDefinition()==typeof(Nullable<>))
                {//Nullable类型
                    return null;
                }
                var ctor = targetType.GetConstructor(new Type[0]);
                if (ctor != null)
                {
                    return ctor.Invoke(null);
                }
                throw new Exception("无法获取目标类型的默认值");
            }
            if (value is JToken jval)
            {
                //if (targetType == typeof(int))
                //{
                //    return jval.ToObject<int>();
                //}
                //else if (targetType == typeof(string))
                //{
                //    return jval.ToObject<string>();
                //}
                //else if (targetType == typeof(decimal))
                //{
                //    return jval.ToObject<decimal>();
                //}
                //else if (targetType == typeof(long))
                //{
                //    return jval.ToObject<long>();
                //}
                //else if (targetType == typeof(bool))
                //{
                //    return jval.ToObject<bool>();
                //}
                //else if (targetType == typeof(DateTime))
                //{
                //    return jval.ToObject<DateTime>();
                //}
                //else if (targetType == typeof(IEnumerable))
                //{
                //    if (jval is JArray)
                //    {

                //    }
                //}
                //if (jval.Type == JTokenType.Array)
                //{

                //}
                return jval.ToObject(targetType);

            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {

            return value;
        }
    }
}
